package cn.itcast.wushangxiantu;

import android.util.Log;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;

/**
 * Okhttp工具类
 */
public class OkhttpUtil {
    public static final MediaType JSON = MediaType.parse("application/json;charset=utf-8");
    public static String [] URL_LOGs={"http://39.102.138.14:8081/WuShangXianTu_1/demo?"};
    public static String URL_LOG = "http://39.102.138.14:8081/WuShangXianTu_1/demo?";//测试服务器
    public static String URL_SOCKET="39.102.138.14";


//   public static String URL_LOG = "http://1.116.206.102:10010/AdventureCountry_1/demo?";//服务器
//    public static String URL_SOCKET="1.116.206.102";
    //public static String URL_LOG = "http://192.168.43.52:8080/AdventureCountry/demo?";//手机
   // public static String URL_LOG = "http://192.168.43.52:8080/AdventureCountry/demo?";//校园网
    //public static String URL_LOG="http://192.168.2.13:8080/AdventureCountry/demo?";


    //预防sql注入
    static String reg = "(?:')|(?:--)|(/\\*(?:.|[\\n\\r])*?\\*/)|"
            + "(\\b(select|update|and|or|delete|insert|trancate|char|into|substr|ascii|declare|exec|count|master|into|drop|execute)\\b)";

    static Pattern sqlPattern = Pattern.compile(reg, Pattern.CASE_INSENSITIVE);// 表示忽略大小写
    public static boolean isSqlValid(String str) {
        Matcher matcher = sqlPattern.matcher(str);
        if (matcher.find()) {
            Log.v("123123123123","参数存在非法字符，请确认：" + matcher.group());
            return false;
        }
        if (str.length()>500) {
            Log.v("123123123123","长度过长");
            return false;
        }
        return true;
    }

    /**
     * post提交请求
     *
     * @param url         服务器地址
     * @param requestBody json数据
     * @param callback    回调
     */
    public static void postRequest(String url, RequestBody requestBody, Callback callback) {
        OkHttpClient okHttpClient = new OkHttpClient();
        Request request = new Request.Builder().url(url).post(requestBody).build();
        okHttpClient.newCall(request).enqueue(callback);
    }

    public static void getRequest(String url, Callback callback) {
        Log.v("urlqingqiu",url);
        if (isSqlValid(url)){
            try {
                Thread.sleep(200);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            OkHttpClient okHttpClient = new OkHttpClient();
            Request request = new Request.Builder().url(url).get().build();
            okHttpClient.newCall(request).enqueue(callback);
        }
    }
}
